package com.dm.utils;

import net.sf.json.JSONObject;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;

/**
 * @author hqw521@qq.com
 * @date 2018/11/15 11:01
 */
public class JsonRequestDataUtil {
    /**
     * 获取接口传递的JSON数据
     *
     * @param request
     * @return
     */
    public static JSONObject getJsonRequestData(HttpServletRequest request) {
        StringBuffer stringBuffer = new StringBuffer();
        try {
            String jsonString = "";
            // 获取application/json格式字符串，返回字符流
            BufferedReader reader = request.getReader();
            // 对字符流进行解析
            while ((jsonString = reader.readLine()) != null) {
                stringBuffer.append(jsonString);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return JSONObject.fromObject(stringBuffer.toString());
    }

    /**
     * 将JSON对象转为JavaBean
     *
     * @param request
     * @param beanClass
     * @return
     */
    public static Object getBean(HttpServletRequest request, Class beanClass) {
        JSONObject jsonObject = getJsonRequestData(request);
        return JSONObject.toBean(jsonObject, beanClass);
    }
}
